package cn.db.controller;

import cn.db.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.Callable;

@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/GetuserInfo")
    public Object getUserInfo(@RequestParam("userId")long userId) {
        //return userService.getUserInfo(userId);

        //多线程并发的方式调用，需要下一个调用不依赖上一个接口的返回值无状态化，且会造成阻塞问题（响应时间是以最长的线程为最终阻塞时间）
        return userService.getUserInfoByThread(userId);
    }

    /**
     * 主线程阻塞导致web服务器吞吐量下降的解决方法
     * 使用servlet3.0异步请求解决阻塞线程提升吞吐量，利用异步线程提升Web服务器的吞吐量
     * @param userId
     * @return
     */

    @RequestMapping("/GetuserInfoAsync")
    public Callable<Object> getUserInfoAsync(@RequestParam("userId")long userId) {
        long TomcatStart =System.currentTimeMillis();//主线程的启动时间
        //开辟一个子线程
        Callable<Object> callable = new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                long ChildStart =System.currentTimeMillis();
                Object result = userService.getUserInfoByThread(userId);
                System.out.println("Child Thread("+Thread.currentThread()+")cost:"+(System.currentTimeMillis()-ChildStart)+"ms");
                return result;
            }
        };
        //Tomcat线程已经释放
        System.out.println("Tomcat Thread("+Thread.currentThread()+")cost:"+(System.currentTimeMillis()-TomcatStart)+"ms");
        return callable;
    }
}

